package com.example.springboot.service.impl;

import cn.hutool.core.date.DateUtil;
import com.example.springboot.domain.Comment;
import com.example.springboot.domain.User;
import com.example.springboot.mapper.CommentMapper;
import com.example.springboot.service.CommentService;
import com.example.springboot.utils.TokenUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class CommentServiceImpl implements CommentService {
    @Autowired
    private CommentMapper commentMapper;

    @Override
    public void add(Comment comment) {
        User user = TokenUtils.getCurrentUser();
        System.out.println("打印获取的comment信息1=============>" + comment);
        comment.setUserId(user.getUserid());
        System.out.println("打印获取的comment信息2=============>" + comment);
        comment.setTime(DateUtil.now());
        System.out.println("打印获取的comment信息3=============>" + comment);
        commentMapper.insert(comment);
        if(comment.getRootId() == null){
            System.out.println("comment的id=============>" + comment.getId());
            comment.setRootId(comment.getId());
            int id = comment.getId();
            commentMapper.updateById(comment,id);
        }
    }

    @Override
    public void deleteById(Integer id) {
        commentMapper.deleteById(id);
    }

    @Override
    public void deleteBatch(List<Integer> ids) {
        for (Integer id : ids) {
            commentMapper.deleteById(id);
        }
    }

    @Override
    public void updateById(Comment comment) {
        int id = comment.getId();
        commentMapper.updateById(comment,id);
    }

    @Override
    public Comment selectById(Integer id) {
        return commentMapper.selectById(id);
    }

    @Override
    public List<Comment> selectAll(Comment comment) {
        return commentMapper.selectAll(comment);
    }

    @Override
    public PageInfo<Comment> selectPage(Comment comment, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<Comment> list = commentMapper.selectAll(comment);
        return PageInfo.of(list);
    }

    @Override
    public Integer selectCount(Integer fid) {
        return commentMapper.selectCount(fid);
    }

//    用遍历实现查询
    @Override
    public List<Comment> selectForUser(Comment comment) {
        List<Comment> commentList = commentMapper.selectForUser(comment);
        for(Comment c : commentList){
            Comment param = new Comment();
            param.setRootId(c.getId());
            List<Comment> children = this.selectAll(param);
            children = children.stream().filter(child -> !child.getId().equals(c.getId())).collect(Collectors.toList());// 进行筛选
            c.setChildren(children);
        }
        return commentList;
    }
}
